<?php

namespace app\common\model;

use think\Model;

use app\common\model\TxArea;

class Address extends Model
{

    // 表名
    protected $name = 'self_address';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = null;

    protected $append = [
        'province',
        'city',
        'county',
    ];

    protected static function init()
    {
        self::beforeInsert(function ($item) {
            if(isset($item['is_default'])  && $item['is_default'] == 1 && isset($item['user_id'])){
                
                Address::where('user_id', $item['user_id'])->update(['is_default' => 0]);
            }
        });

        self::beforeUpdate(function ($item) {
            if(isset($item['is_default'])  && $item['is_default'] == 1 && isset($item['user_id'])){
                Address::where('user_id', $item['user_id'])->update(['is_default' => 0]);
            }
        });
    }

    public function getProvinceAttr($value, $data)
    {
        $province_id = isset($data['province_id']) ?  $data['province_id'] : 0;    

        $res = $province_id ? TxArea::cache(300)->where('area_code',$province_id)->value('name') : '';

        return $res ? $res : '';
    }

    public function getCityAttr($value, $data)
    {
        $city_id = isset($data['city_id']) ?  $data['city_id'] : 0;    

        $res = $city_id ? TxArea::cache(300)->where('area_code',$city_id)->value('name') : '';

        return $res ? $res : '';
    }

    public function getCountyAttr($value, $data)
    {
        $county = isset($data['county_id']) ?  $data['county_id'] : 0;    

        $res =  $county ? TxArea::cache(300)->where('area_code',$county)->value('name') : '';

        return $res ? $res : '';
    }

    
}
